<template>
    <div>
         <!-- 添加编辑对话框 -->
         <el-dialog v-model="props.updateDialog" title="修改生产领料单" width="70%" @close="closeDialog" 
         @open="handleOpen">
            <el-form :model="form" :rules="rules" ref="ruleForm"  label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="领料单编号" prop="issueCode">
                            <el-input v-model="form.issueCode" autocomplete="off" placeholder="请输入领料单编号"></el-input>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="2">
                        <el-switch v-model="isSwitch" active-value="自动生成" @change="switchCode">
                        </el-switch>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="领料单名称" prop="issueName">
                            <el-input v-model="form.issueName" autocomplete="off" placeholder="请输入领料单名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="领料日期" prop="issueDate">
                            <el-date-picker v-model="form.issueDate" type="date" placeholder="请选择领料日期"
                                style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="选择仓库">
                            <el-cascader v-model="form.warehouseNames" ref="cascader" :options="options"
                                @change="" placeholder="请选择仓库" clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单据状态">
                            <el-select v-model="form.status" placeholder="请选择状态" disabled>
                                <el-option v-for="item in orderStatus" :key="item.value" :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="生产工单" prop="workorderCode">
                            <el-input v-model="form.workorderCode" placeholder="请输入工单编码">
                                <template #append>
                                    <el-button :icon="Search" @click="findWorkorder"></el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户编码" prop="clientCode">
                            <el-input v-model="form.clientCode" placeholder="请输入客户编码"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称" prop="clientName">
                            <el-input v-model="form.clientName" placeholder="请输入客户名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="form.remark" placeholder="请输入内容"
                                :autosize="{ minRows: 2, maxRows: 4 }"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            
            <!-- 物料信息 -->
            <div>
                <el-divider>
                    <span>物料信息</span>
                </el-divider>
                <el-tabs type="border-card" class="shadow-tabs">
                    <div style="padding: 10px;">
                        <el-button type="primary" :icon="Plus" plain @click="onAddMaterial">新增</el-button>
                    </div>
                    <el-row>
                        <el-col :span="24">
                            <el-table :data="materialResult" style="width: 100%; padding: 10px;">
                            <!-- <el-table-column type="selection"  width="40"></el-table-column> -->
                            <el-table-column prop="materialProductCode" label="产品物料编码" width="120" align="center"></el-table-column>
                            <el-table-column prop="productName" label="产品物料名称" width="120" align="center"></el-table-column>
                            <el-table-column prop="specificationAndModel" label="规格型号" width="120" align="center"></el-table-column>
                            <el-table-column prop="quantityIssued" label="领料数量" width="120" align="center"></el-table-column>
                            <el-table-column prop="unitOfMeasure" label="单位" width="120" align="center"></el-table-column>
                            <el-table-column prop="batchCode" label="批次号" width="120" align="center"></el-table-column>
                            <el-table-column prop="warehouseName" label="仓库名称" width="120" align="center"></el-table-column>
                            <el-table-column prop="locationName" label="库区名称" width="120" align="center"></el-table-column>
                            <el-table-column prop="areaName" label="库位名称" width="120" align="center"></el-table-column>
                            <el-table-column prop="remark" label="备注" width="120" align="center"></el-table-column>
                            <el-table-column label="操作" width="150" align="center">
                                <template #default="scope">
                                    <el-button type="text" :icon="EditPen" @click="onUpdateMaterial(scope.row)">修改</el-button>
                                    <el-button type="text" :icon="Delete" @click="onDelMaterial(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                            </el-table>
                        </el-col>
                    </el-row>
                    <!-- 分页组件 -->
                    <el-row>
                        <el-col :span="24">
                            <div class="pagination">
                                <el-pagination :current-page="WUliao.currentPage" :page-size="WUliao.pageSize"
                                :page-sizes="pageSizes" :total="pageResult.total" layout="total, sizes, prev, pager, next, jumper"
                                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                            </div>
                        </el-col>
                    </el-row>
                </el-tabs>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirmAdd(ruleForm)">确认</el-button>
                <el-button @click="closeDialog">取消</el-button>
                </div>
            </template>
        </el-dialog>

        
    <FindWorkorder :findWorkorderDialog="findWorkorderVisible" @close-dialog="colseDialog" @rowDataP="rowDataP"/>
    
    <AddWUliaoDialog :addWUliaoDialog="addDialogVisible" :form="form" @close-dialog="colseDialog" />

    <UpdateWUliaoDialog :updateWUliaoDialog="updateDialogVisible" :updateWLFrom="updateWLFrom" @close-dialog="colseDialog" />
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch, nextTick } from 'vue'
const props = defineProps(['updateDialog','updateFrom']);
const emit = defineEmits(['close-dialog']);
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Delete, Plus, EditPen, Check } from '@element-plus/icons-vue';
import { findWarehousesList } from '@/apis/xms/index';
import { updatePicking , findWmIssueLine, deleteWmIssueLine} from '@/apis/zs/index';
import FindWorkorder from '@/components/ProductionPicking/FindWorkorder.vue';
import AddWUliaoDialog from '@/components/ProductionPicking/AddWUliaoDialog.vue';
import UpdateWUliaoDialog from './UpdateWUliaoDialog.vue';

const findWorkorderVisible = ref(false);// 工单查找弹窗
const addDialogVisible = ref(false);//新增物料弹窗
const updateDialogVisible = ref(false);//修改物料弹窗

const orderStatus = ref([//状态下拉
        { label:"草稿", value:"PREPARE" },
        { label:"已确认" ,value:"CONFIRMED" },
        { label:"审批中" ,value:"APPROVING" },
        { label:"已审批" ,value:"APPROVED" },
        { label:"已完成" ,value:"FINISHED" },
        { label:"已拒绝" ,value:"REFUSE" },
        { label:"已生成生产订单", value:"WORK_ORDER_FINISHED" },
]);

let form = reactive({
    issueId: '',
    issueCode: '',
    issueName: '',
    issueDate: '',
    warehouseNames: [],
    status: 'PREPARE',
    workorderId: '',
    workorderCode: '',
    clientCode: '',
    clientName: '',
    remark: '',
    warehouseId: '',
    warehouseName: '',
    areaId: '',
    areaName: '',
    locationId: '',
    locationName: ''
});
watch(() => props.updateFrom, (newVal) => {
    if (newVal) {
        Object.assign(form, newVal);
    }
});

const options = ref([]); //仓库列表
const ruleForm = ref(null); // 表单
const resetFormAdd = reactive({ ... form });//重置表单
const rules = ref({//表单验证规则
    issueCode: [{ required: true, message: '请输入领料单编号', trigger: 'blur' }],
    issueName: [{ required: true, message: '请输入领料单名称', trigger: 'blur' }],
    issueDate: [{ required: true, message: '请选择领料日期', trigger: 'change' }],
    workorderCode: [{ required: true, message: '请输入生产工单编码', trigger: 'blur' }]
});

const handleOpen = () => {//打开对话框时处理
    nextTick(()=>{
        ruleForm.value.clearValidate();//清除表单验证
        loadList();
    })
};

const findWorkorder = () => {//查找工单
    findWorkorderVisible.value = true;
};

const rowDataP = (row) => {//选择工单
    form.workorderId = row.workorderId;
    form.workorderCode = row.workorderCode;
    form.clientCode = row.clientCode;
    form.clientName = row.clientName;
};
const confirmAdd = (value) => { //确认提交
    if(!value)return;
    value.validate((valid) => {
        if (valid) {
            console.log("form:", form);
            updatePicking(form).then(res => {
                if( res == "成功") {
                    ElMessage.success('修改成功');
                    closeDialog();
                }else{
                    ElMessage.error('修改失败');
                }
            }).catch(err => {
                ElMessage.error('修改失败');
            });
        } else {
            ElMessage.error('请检查输入项');
        }
    });
};

onMounted( async()=>{
    await findWarehousesList().then(res=>{
        options.value =res;
        console.log("仓库列表获取成功:", options.value);
    }); // 获取仓库列表

    // 确保 form.warehouseNames 是一个数组并且有三个元素（仓库ID、库区ID、库位ID）
    if (Array.isArray(form.warehouseNames) && form.warehouseNames.length === 3) {
        const [warehouseId, areaId, locationId] = form.warehouseNames;
        // 查找仓库信息
        const warehouse = options.value.find(item => item.value === warehouseId);
        if (warehouse) {
            form.warehouseId = warehouseId;
            form.warehouseName = warehouse.label;

            // 查找库区信息
            const area = warehouse.children.find(it => it.value === areaId);
            if (area) {
                form.areaId = areaId;
                form.areaName = area.label + "";

                // 查找库位信息
                const location = area.children.find(i => i.value === locationId);
                if (location) {
                    form.locationId = locationId;
                    form.locationName = location.label;
                }
            }
        }
        console.log("仓库信息设置完成:", form);
    } else {
        console.warn("无效的仓库名称数组:", form.warehouseNames);
    }
});

const pageResult = ref({});//分页信息
const materialResult = ref([]);//物料信息

const WUliao = reactive({
    currentPage: 1,
    pageSize: 10,
    id : ''
});

const loadList =async () => {
    await findWmIssueLine({id:form.issueId}).then(res => {//获取物料信息
        pageResult.value = res; //设置物料信息
        materialResult.value = pageResult.value.records; //设置物料信息
        console.log("物料信息获取成功:", materialResult.value);
    }); 
};
onMounted(()=>{//获取物料信息
    loadList();
})

// 分页大小
const pageSizes = [10, 20, 30, 40, 50];
//处理分页大小变化
const handleSizeChange = async (size) => {
    WUliao.pageSize = size;
    loadList();
}
//处理当前页码变化
const handleCurrentChange = async (currentPage) => {
    WUliao.currentPage = currentPage
    loadList();
}


const onAddMaterial = () => {//新增物料
    addDialogVisible.value = true;
};
let updateWLFrom = reactive({
    lineId: '',
    materialProductCode: '',
    productName: '',
    quantityIssued: 0,
    specificationAndModel: '',
    unitOfMeasure: '',
    batchCode: '',
    warehouseName: '',
    areaName: '',
    locationName: '',
    remark: ''
});//修改物料表单
const onUpdateMaterial = (row) => {//修改物料
    updateDialogVisible.value = true;
    Object.assign(updateWLFrom, row);
    console.log("修改物料信息:", updateWLFrom);

};

const onDelMaterial = (row) => {//删除物料
    ElMessageBox.confirm(`是否确认删除生产领料单行编号为"${row.lineId}"的数据项？`,'系统提示',{
        ConfirmButtonText: '确定',
        CancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        console.log("删除物料信息:", row);
        deleteWmIssueLine(row.lineId).then(res => {
            if(res == "成功") {
                ElMessage.success('删除成功');
                loadList();
            }else{
                ElMessage.error('删除失败');
            }
        }).catch(err => {
            ElMessage.error('删除失败');
        });
    }).catch(() => {
        console.log('取消删除');
    });
};


const closeDialog = () => {//关闭弹窗
    Object.assign(form, resetFormAdd);
    isSwitch.value = false;
    emit('close-dialog');
};

const colseDialog = async() => {//关闭弹窗
    findWorkorderVisible.value = false;
    addDialogVisible.value = false;
    updateDialogVisible.value = false;
    loadList();
};

const isSwitch = ref(false);//生成编码开关更新状态
// const codeCounter = ref(0);//用于生成编码的计数器
const switchCode = (value) => {//生成编码开关
    const Code = createID();
    if (value) {
        form.issueCode = Code;
    } else {
        form.issueCode = '';
    }
};
function createID() {//工单编码生成
    let code = 'ISSUE';
    let date = new Date();
    let year = date.getFullYear();
    let month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份补零
    let strDate = ('0' + date.getDate()).slice(-2); // 日期补零
    code = code + year + month + strDate + Math.floor(Math.random() * 10000);
    // code = code + year + month + strDate + ('0000' + (++codeCounter.value)).slice(-4); // 后面拼接递增的数字
    return code;
};
</script>

<style  scoped>
.shadow-tabs {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;
}
.pagination {
    margin-top: 20px;
    margin-left: 20px;
    text-align: right;
}
</style>
